-- ============================================
-- ROCKET CASINO - MACHINE A SOUS
-- Architecture :
--   - Le COMPUTER : uniquement la connexion au clavier physique
--     (pseudo + mot de passe). Rien d'autre ne se joue ici.
--   - Le MONITOR : banniere de repos (Poke Ball) tant que personne
--     n'est connecte, puis le jeu complet (100% tactile) une fois
--     connecte, avec une interface inspiree d'une machine a sous
--     classique (compteurs LCD, fenetres de rouleaux, badges),
--     redessinee dans un style Team Rocket original.
--
-- Fichier requis dans le meme dossier : client_solde.lua
-- ============================================

local bank = dofile("client_solde.lua")
math.randomseed(os.epoch and os.epoch("utc") or os.time())

local FRAME_DELAY = 0.1
local ROTATION_SPEED = 0.22
local SUBTITLE_TEXT = "   *** PREPARE FOR TROUBLE * MAKE IT DOUBLE ***   BIENVENUE AU ROCKET CASINO   *** LES JACKPOTS SONT (PRESQUE) GARANTIS ***   "
local BET_MIN, BET_MAX, BET_STEP = 1, 20, 1

local currentPlayer = nil

-------------------------------
-- MONITEUR
-------------------------------
local mon = peripheral.find("monitor")
if not mon then
    error("Aucun moniteur trouve ! Connecte un Advanced Monitor a cet ordinateur.", 0)
end

mon.setTextScale(0.5)
mon.setBackgroundColor(colors.black)
mon.clear()
local W, H = mon.getSize()

-------------------------------
-- OUTILS DE DESSIN BAS NIVEAU
-------------------------------

local function newCanvas(bg)
    local c = {}
    for y = 1, H do
        c[y] = {}
        for x = 1, W do
            c[y][x] = { bg = bg, ch = " ", fg = colors.white }
        end
    end
    return c
end

local function px(canvas, x, y, bg, ch, fg)
    x, y = math.floor(x + 0.5), math.floor(y + 0.5)
    if x >= 1 and x <= W and y >= 1 and y <= H then
        local cell = canvas[y][x]
        if bg then cell.bg = bg end
        if ch then
            cell.ch = ch
            cell.fg = fg or cell.fg
        end
    end
end

local function render(canvas)
    local toBlit = colors.toBlit
    for y = 1, H do
        local row = canvas[y]
        local chars, fgs, bgs = {}, {}, {}
        for x = 1, W do
            local cell = row[x]
            chars[x] = cell.ch
            fgs[x] = toBlit(cell.fg)
            bgs[x] = toBlit(cell.bg)
        end
        mon.setCursorPos(1, y)
        mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
    end
end

local function fillEllipse(canvas, cx, cy, rx, ry, color)
    if rx <= 0 or ry <= 0 then return end
    for y = math.floor(cy - ry), math.ceil(cy + ry) do
        local dy = (y - cy) / ry
        local t = 1 - dy * dy
        if t >= 0 then
            local dx = rx * math.sqrt(t)
            for x = math.floor(cx - dx), math.ceil(cx + dx) do
                px(canvas, x, y, color)
            end
        end
    end
end

local function fillRect(canvas, x1, y1, x2, y2, color)
    for y = y1, y2 do
        for x = x1, x2 do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleUp(canvas, cx, baseY, tipY, halfWidth, color)
    local height = baseY - tipY
    if height <= 0 then return end
    for y = tipY, baseY do
        local f = (y - tipY) / height
        local w = halfWidth * f
        for x = math.floor(cx - w), math.ceil(cx + w) do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleDown(canvas, cx, baseY, tipY, halfWidth, color)
    local height = tipY - baseY
    if height <= 0 then return end
    for y = baseY, tipY do
        local f = (tipY - y) / height
        local w = halfWidth * f
        for x = math.floor(cx - w), math.ceil(cx + w) do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleSide(canvas, baseX, tipX, cy, halfHeight, color)
    local width = tipX - baseX
    if width == 0 then return end
    local step = width > 0 and 1 or -1
    for x = baseX, tipX, step do
        local f = (x - baseX) / width
        local hh = halfHeight * (1 - f)
        for y = math.floor(cy - hh), math.ceil(cy + hh) do
            px(canvas, x, y, color)
        end
    end
end

-------------------------------
-- MINI POLICE PIXEL 5x7
-------------------------------

local FONT = {
    R = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" },
    O = { ".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###." },
    C = { ".####", "#....", "#....", "#....", "#....", "#....", ".####" },
    K = { "#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#" },
    E = { "#####", "#....", "#....", "####.", "#....", "#....", "#####" },
    T = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "..#.." },
    A = { ".###.", "#...#", "#...#", "#####", "#...#", "#...#", "#...#" },
    S = { ".####", "#....", "#....", ".###.", "....#", "....#", "####." },
    I = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "#####" },
    N = { "#...#", "##..#", "#.#.#", "#..##", "#...#", "#...#", "#...#" },
}

local function drawGlyph(canvas, pattern, x0, y0, scale, color)
    for row = 1, #pattern do
        local line = pattern[row]
        for col = 1, #line do
            if line:sub(col, col) == "#" then
                for sy = 0, scale - 1 do
                    for sx = 0, scale - 1 do
                        px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
                    end
                end
            end
        end
    end
end

local function drawText(canvas, x, y, text, fg, bg)
    for i = 1, #text do
        px(canvas, x + i - 1, y, bg, text:sub(i, i), fg)
    end
end

-------------------------------
-- BANNIERE DE REPOS
-------------------------------

local CHASE_COLORS = { colors.yellow, colors.orange, colors.red, colors.orange }
local function drawMarquee(canvas, tick)
    local n = #CHASE_COLORS
    for x = 1, W do
        local c = CHASE_COLORS[((x + tick) % n) + 1]
        px(canvas, x, 1, c)
        px(canvas, x, H, c)
    end
    for y = 1, H do
        local c = CHASE_COLORS[((y + tick) % n) + 1]
        px(canvas, 1, y, c)
        px(canvas, W, y, c)
    end
end

local ACCENT_COLORS = { colors.yellow, colors.orange, colors.white, colors.orange }
local function drawBigTitle(canvas, tick, word1, word2, redIdx1, redIdx2)
    local LETTER_W, GAP_W, WORD_GAP = 5, 1, 4

    local function wordUnits(word)
        return #word * LETTER_W + (#word - 1) * GAP_W
    end
    local totalUnits = wordUnits(word1) + WORD_GAP + wordUnits(word2)

    local scale = math.max(1, math.floor((W - 6) / totalUnits))
    local totalWidth = totalUnits * scale
    local startX = math.max(2, math.floor((W - totalWidth) / 2) + 1)
    local startY = 3

    local accent = ACCENT_COLORS[(math.floor(tick / 3) % #ACCENT_COLORS) + 1]

    local function drawWord(word, x, redLetterIndex)
        for i = 1, #word do
            local letter = word:sub(i, i)
            local pattern = FONT[letter]
            local color = (redLetterIndex and i == redLetterIndex) and colors.red or accent
            if pattern then
                drawGlyph(canvas, pattern, x + 1, startY + 1, scale, colors.black)
                drawGlyph(canvas, pattern, x, startY, scale, color)
            end
            x = x + (LETTER_W + GAP_W) * scale
        end
        return x
    end

    local cursor = startX
    cursor = drawWord(word1, cursor, redIdx1)
    cursor = cursor + (WORD_GAP - GAP_W) * scale
    drawWord(word2, cursor, redIdx2)

    return startY + 7 * scale + 2
end

local function drawSubtitle(canvas, tick)
    local y = H - 2
    local len = #SUBTITLE_TEXT
    local offset = tick % len
    local scrolled = SUBTITLE_TEXT:sub(offset + 1) .. SUBTITLE_TEXT:sub(1, offset)
    local visible = scrolled:sub(1, math.max(0, W - 4))
    drawText(canvas, 3, y, visible, colors.yellow, colors.black)
end

local function drawPokeball(canvas, cx, cy, r, angle)
    local squish = math.max(0.12, math.abs(math.cos(angle)))
    local rx = r * squish
    local ry = r

    fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

    for y = math.floor(cy - ry), math.ceil(cy + ry) do
        local dy = (y - cy) / ry
        local t = 1 - dy * dy
        if t >= 0 then
            local dx = rx * math.sqrt(t)
            local color
            if y < cy - ry * 0.08 then
                color = colors.black
            elseif y > cy + ry * 0.08 then
                color = colors.red
            else
                color = colors.lightGray
            end
            for x = math.floor(cx - dx), math.ceil(cx + dx) do
                px(canvas, x, y, color)
            end
        end
    end

    for x = math.floor(cx - rx), math.ceil(cx + rx) do
        px(canvas, x, cy, colors.black)
    end

    local buttonR = math.max(1, r * 0.28 * squish)
    fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
    fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
    fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

    if squish > 0.55 then
        local scale = math.max(1, math.floor(r * squish / 5))
        local rx0 = math.floor(cx - 2 * scale)
        local ry0 = math.floor(cy - ry * 0.75)
        for dx = -1, 1 do
            for dy = -1, 1 do
                if dx ~= 0 or dy ~= 0 then
                    drawGlyph(canvas, FONT.R, rx0 + dx, ry0 + dy, scale, colors.black)
                end
            end
        end
        drawGlyph(canvas, FONT.R, rx0, ry0, scale, colors.red)
    end
end

local function drawIdleFrame(tick, angle, flashHint)
    local canvas = newCanvas(colors.black)
    drawMarquee(canvas, tick)
    local contentTop = drawBigTitle(canvas, tick, "ROCKET", "CASINO", 1, 1)

    local centerX = math.floor(W / 2)
    local availableH = math.max(6, (H - 3) - contentTop)
    local centerY = contentTop + math.floor(availableH / 2)
    local shapeR = math.floor(math.min(W * 0.22, availableH * 0.45))
    drawPokeball(canvas, centerX, centerY, shapeR, angle)

    local hint = flashHint and "*** VA TAPER TON PSEUDO SUR L'ORDINATEUR ! ***"
        or "Connecte-toi sur l'ordinateur pour jouer"
    local hx = math.max(2, math.floor((W - #hint) / 2) + 1)
    drawText(canvas, hx, math.min(H - 4, centerY + shapeR + 2), hint,
        flashHint and colors.red or colors.white, colors.black)

    drawSubtitle(canvas, tick)
    render(canvas)
end

local function idleLoop()
    local tick, angle = 0, 0
    local flashTicks = 0
    while currentPlayer == nil do
        drawIdleFrame(tick, angle, flashTicks > 0)
        if flashTicks > 0 then flashTicks = flashTicks - 1 end
        angle = angle + ROTATION_SPEED
        tick = tick + 1

        local timerId = os.startTimer(FRAME_DELAY)
        local waiting = true
        while waiting do
            local ev, a = os.pullEvent()
            if ev == "timer" and a == timerId then
                waiting = false
            elseif ev == "monitor_touch" then
                flashTicks = math.floor(1.5 / FRAME_DELAY)
            end
        end
    end
end

-------------------------------
-- SYMBOLES DE LA MACHINE A SOUS (dessins originaux)
-------------------------------

local function drawSymbolSeven(canvas, cx, cy, r)
    fillEllipse(canvas, cx, cy, r, r, colors.black)
    fillEllipse(canvas, cx, cy, r * 0.8, r * 0.8, colors.red)
    local scale = math.max(1, math.floor(r / 3))
    drawGlyph(canvas, FONT.T, math.floor(cx - 2.5 * scale), math.floor(cy - 3.5 * scale), scale, colors.yellow)
end

local function drawSymbolStar(canvas, cx, cy, r)
    fillTriangleUp(canvas, cx, cy, cy - r, r * 0.24, colors.yellow)
    fillTriangleDown(canvas, cx, cy, cy + r, r * 0.24, colors.yellow)
    fillTriangleSide(canvas, cx, cx - r, cy, r * 0.24, colors.yellow)
    fillTriangleSide(canvas, cx, cx + r, cy, r * 0.24, colors.yellow)
    fillEllipse(canvas, cx, cy, r * 0.22, r * 0.22, colors.white)
end

local function drawSymbolFlame(canvas, cx, cy, r)
    fillEllipse(canvas, cx, cy + r * 0.15, r * 0.7, r * 0.6, colors.red)
    fillTriangleUp(canvas, cx, cy + r * 0.15, cy - r, r * 0.55, colors.red)
    fillEllipse(canvas, cx, cy + r * 0.25, r * 0.45, r * 0.4, colors.orange)
    fillTriangleUp(canvas, cx, cy + r * 0.25, cy - r * 0.55, r * 0.32, colors.orange)
    fillEllipse(canvas, cx, cy + r * 0.35, r * 0.2, r * 0.2, colors.yellow)
end

local function drawSymbolCoin(canvas, cx, cy, r)
    fillEllipse(canvas, cx, cy, r, r, colors.brown)
    fillEllipse(canvas, cx, cy, r * 0.8, r * 0.8, colors.orange)
    fillEllipse(canvas, cx, cy, r * 0.55, r * 0.55, colors.yellow)
end

local function drawSymbol(canvas, id, cx, cy, r)
    if id == "BALL" then
        drawPokeball(canvas, cx, cy, r, 0)
    elseif id == "SEVEN" then
        drawSymbolSeven(canvas, cx, cy, r)
    elseif id == "STAR" then
        drawSymbolStar(canvas, cx, cy, r)
    elseif id == "FLAME" then
        drawSymbolFlame(canvas, cx, cy, r)
    elseif id == "COIN" then
        drawSymbolCoin(canvas, cx, cy, r)
    end
end

-------------------------------
-- TABLE DES GAINS
-------------------------------

local SYMBOLS = {
    { id = "BALL",  weight = 1, mult = 20 },
    { id = "SEVEN", weight = 2, mult = 10 },
    { id = "STAR",  weight = 3, mult = 7 },
    { id = "FLAME", weight = 4, mult = 5 },
    { id = "COIN",  weight = 5, mult = 3 },
}

local TOTAL_WEIGHT = 0
for _, s in ipairs(SYMBOLS) do TOTAL_WEIGHT = TOTAL_WEIGHT + s.weight end

local MULT_BY_ID = {}
for _, s in ipairs(SYMBOLS) do MULT_BY_ID[s.id] = s.mult end

local function pickSymbol()
    local roll = math.random(TOTAL_WEIGHT)
    local acc = 0
    for _, s in ipairs(SYMBOLS) do
        acc = acc + s.weight
        if roll <= acc then return s.id end
    end
    return SYMBOLS[#SYMBOLS].id
end

local function evaluateWin(symbols, bet)
    if symbols[1] == symbols[2] and symbols[2] == symbols[3] then
        local mult = MULT_BY_ID[symbols[1]] or 1
        return bet * mult, "JACKPOT ! 3x " .. symbols[1] .. " (x" .. mult .. ")"
    elseif symbols[1] == symbols[2] or symbols[2] == symbols[3] or symbols[1] == symbols[3] then
        return bet, "Petit gain, mise remboursee !"
    else
        return 0, "Perdu... retente ta chance !"
    end
end

-------------------------------
-- ECRAN DE JEU : inspire d'une machine a sous classique
-- (compteurs LCD, fenetres de rouleaux, badges laterales,
--  indicateurs de rotation), redessine en style Team Rocket original
-------------------------------

local ROW_KEYS = { "top", "mid", "bot" }

-- Calcule la disposition horizontale : badge | rouleaux (x3) | badge,
-- toujours centree sur la largeur du moniteur.
local function computeLayout()
    local badgeW = math.max(3, math.floor(W * 0.07))
    local badgeGap = math.max(1, math.floor(W * 0.02))
    local reelGap = math.max(1, math.floor(W * 0.02))

    local usable = W - 2 * badgeW - 2 * badgeGap - 2 * reelGap - 4
    local reelPanelW = math.max(5, math.floor(usable / 3))
    local reelsTotalW = reelPanelW * 3 + reelGap * 2
    local contentW = badgeW * 2 + badgeGap * 2 + reelsTotalW

    local startX = math.max(2, math.floor((W - contentW) / 2) + 1)
    local leftBadgeX = startX
    local reelsX = leftBadgeX + badgeW + badgeGap
    local rightBadgeX = reelsX + reelsTotalW + badgeGap

    return {
        leftBadgeX = leftBadgeX,
        rightBadgeX = rightBadgeX,
        reelsX = reelsX,
        badgeW = badgeW,
        reelPanelW = reelPanelW,
        reelGap = reelGap,
    }
end

local function drawGameScreen(tick, player, credit, lastGain, bet, reels, message, lockedCount)
    local canvas = newCanvas(colors.black)

    -- cadre simple
    for x = 1, W do
        px(canvas, x, 1, colors.red)
        px(canvas, x, H, colors.red)
    end
    for y = 1, H do
        px(canvas, 1, y, colors.red)
        px(canvas, W, y, colors.red)
    end

    -- petites flammes decoratives dans les coins bas
    fillTriangleUp(canvas, 4, H - 1, H - 6, 2, colors.orange)
    fillTriangleUp(canvas, W - 3, H - 1, H - 6, 2, colors.orange)

    -- barre de controle tactile en haut
    local buttons = {}
    local btnY = 2
    local cursor = 3
    local function btn(id, label, bg, fg)
        local text = " " .. label .. " "
        for i = 1, #text do
            px(canvas, cursor + i - 1, btnY, bg, text:sub(i, i), fg or colors.white)
        end
        table.insert(buttons, { id = id, x1 = cursor, x2 = cursor + #text - 1, y1 = btnY, y2 = btnY })
        cursor = cursor + #text + 1
    end
    btn("BET_DOWN", "-MISE", colors.red)
    btn("BET_UP", "+MISE", colors.green)
    btn("SPIN", "TOURNER x" .. bet, colors.orange, colors.black)
    btn("QUIT", "QUITTER", colors.gray)

    -- afficheurs LCD : CREDIT / GAIN, toujours centres en paire
    local lcdY1, lcdY2 = 4, 6
    local lcdW = math.max(8, math.floor(W * 0.26))
    local pairGap = math.max(2, math.floor(W * 0.03))
    local pairW = lcdW * 2 + pairGap
    local leftLcdX1 = math.floor((W - pairW) / 2) + 1
    local leftLcdX2 = leftLcdX1 + lcdW
    local rightLcdX1 = leftLcdX2 + pairGap
    local rightLcdX2 = rightLcdX1 + lcdW

    fillRect(canvas, leftLcdX1, lcdY1, leftLcdX2, lcdY2, colors.black)
    fillRect(canvas, rightLcdX1, lcdY1, rightLcdX2, lcdY2, colors.black)
    drawText(canvas, leftLcdX1 + 1, lcdY1, "CREDIT", colors.gray, colors.black)
    drawText(canvas, rightLcdX1 + 1, lcdY1, "GAIN", colors.gray, colors.black)
    drawText(canvas, leftLcdX1 + 1, lcdY1 + 1, tostring(credit), colors.lime, colors.black)
    drawText(canvas, rightLcdX1 + 1, lcdY1 + 1, tostring(lastGain), colors.lime, colors.black)

    -- zone de jeu : badges + rouleaux
    local layout = computeLayout()
    local reelsTopY = 9
    local reelH = math.max(9, math.floor(H * 0.4))
    local reelsBottomY = reelsTopY + reelH

    local rowY = {
        reelsTopY + math.floor(reelH / 6),
        reelsTopY + math.floor(reelH / 2),
        reelsTopY + math.floor(reelH * 5 / 6),
    }

    local badgeVals = { "2", "3", "2" }
    local badgeColors = { colors.orange, colors.red, colors.orange }
    for i = 1, 3 do
        local halfW = math.max(1, math.floor(layout.badgeW / 2))
        fillEllipse(canvas, layout.leftBadgeX + halfW, rowY[i], halfW, 1, badgeColors[i])
        fillEllipse(canvas, layout.rightBadgeX + halfW, rowY[i], halfW, 1, badgeColors[i])
        drawText(canvas, layout.leftBadgeX + halfW, rowY[i], badgeVals[i], colors.black, badgeColors[i])
        drawText(canvas, layout.rightBadgeX + halfW, rowY[i], badgeVals[i], colors.black, badgeColors[i])
    end

    for c = 1, 3 do
        local x1 = layout.reelsX + (c - 1) * (layout.reelPanelW + layout.reelGap)
        local x2 = x1 + layout.reelPanelW
        fillRect(canvas, x1 - 1, reelsTopY - 1, x2 + 1, reelsBottomY + 1, colors.black)
        fillRect(canvas, x1, reelsTopY, x2, reelsBottomY, colors.lightGray)

        for r = 1, 3 do
            local id = reels[c][ROW_KEYS[r]]
            local cx = math.floor((x1 + x2) / 2)
            local cy = rowY[r]
            local symR = math.max(1, math.floor(math.min(layout.reelPanelW, reelH / 3) * 0.38))
            drawSymbol(canvas, id, cx, cy, symR)
        end

        -- ligne de paiement (rangee du milieu surlignee)
        local paylineTopY = rowY[2] - math.floor(reelH / 6) + 1
        local paylineBotY = rowY[2] + math.floor(reelH / 6) - 1
        for x = x1, x2 do
            px(canvas, x, paylineTopY, colors.red)
            px(canvas, x, paylineBotY, colors.red)
        end
    end

    -- indicateurs de rotation sous chaque rouleau
    local circleY = reelsBottomY + 3
    for c = 1, 3 do
        local x1 = layout.reelsX + (c - 1) * (layout.reelPanelW + layout.reelGap)
        local x2 = x1 + layout.reelPanelW
        local cx = math.floor((x1 + x2) / 2)
        local locked = lockedCount and (c <= lockedCount)
        fillEllipse(canvas, cx, circleY, 1.4, 1.4, colors.black)
        fillEllipse(canvas, cx, circleY, 1, 1, locked and colors.yellow or colors.gray)
    end

    -- message de jeu
    local msgY = circleY + 3
    local msgX = math.max(2, math.floor((W - #message) / 2) + 1)
    drawText(canvas, msgX, msgY, message, colors.yellow, colors.black)

    render(canvas)
    return buttons
end

-- Animation : les rouleaux s'arretent l'un apres l'autre
local function spinAnimation(player, creditDuringSpin, bet)
    local reels = {}
    for i = 1, 3 do
        reels[i] = { top = pickSymbol(), mid = pickSymbol(), bot = pickSymbol() }
    end
    local stopTicks = { 10, 16, 22 }
    local maxTick = stopTicks[3]

    for tick = 1, maxTick do
        local lockedCount = 0
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = pickSymbol()
            else
                lockedCount = lockedCount + 1
            end
        end
        drawGameScreen(tick, player, creditDuringSpin, "...", bet, reels, "Ca tourne...", lockedCount)
        sleep(0.06)
    end

    return reels
end

local function runGameSession(player)
    local credit = bank.getBalance(player)
    local bet = BET_MIN
    local lastGain = 0
    local message = "Place ta mise et lance les rouleaux !"
    local reels = {
        { top = "COIN", mid = "COIN", bot = "COIN" },
        { top = "COIN", mid = "COIN", bot = "COIN" },
        { top = "COIN", mid = "COIN", bot = "COIN" },
    }
    local tick = 0
    local playing = true

    while playing do
        credit = bank.getBalance(player)
        local buttons = drawGameScreen(tick, player, credit, lastGain, bet, reels, message, nil)
        tick = tick + 1

        local _, _, x, y = os.pullEvent("monitor_touch")
        local pressed = nil
        for _, b in ipairs(buttons) do
            if x >= b.x1 and x <= b.x2 and y >= b.y1 and y <= b.y2 then
                pressed = b.id
                break
            end
        end

        if pressed == "BET_DOWN" then
            bet = math.max(BET_MIN, bet - BET_STEP)
        elseif pressed == "BET_UP" then
            bet = math.min(BET_MAX, bet + BET_STEP)
        elseif pressed == "SPIN" then
            if credit < bet then
                message = "Solde insuffisant !"
            else
                local newBal, err = bank.addBalance(player, -bet)
                if not newBal then
                    message = err or "Erreur banque, reessaie."
                else
                    reels = spinAnimation(player, newBal, bet)
                    local gain, resultMsg = evaluateWin({ reels[1].mid, reels[2].mid, reels[3].mid }, bet)
                    if gain > 0 then
                        bank.addBalance(player, gain)
                    end
                    lastGain = gain
                    message = resultMsg
                    credit = bank.getBalance(player)
                end
            end
        elseif pressed == "QUIT" then
            playing = false
        end
    end
end

local function monitorMainLoop()
    while true do
        idleLoop()
        if currentPlayer then
            runGameSession(currentPlayer)
            currentPlayer = nil
        end
    end
end

-------------------------------
-- COMPUTER : connexion au clavier physique UNIQUEMENT
-------------------------------

local function authenticateKeyboard()
    term.setBackgroundColor(colors.black)
    term.clear()
    term.setCursorPos(1, 1)
    term.setTextColor(colors.red)
    print("=== ROCKET CASINO ===")
    term.setTextColor(colors.white)
    write("Pseudo Minecraft : ")
    local username = read()

    while true do
        write("Mot de passe : ")
        local password = read("*")
        local ok, err = bank.authenticate(username, password)
        if ok then
            term.setTextColor(colors.lime)
            print("Connecte ! Va jouer sur l'ecran mural.")
            return username
        else
            term.setTextColor(colors.red)
            print(err or "Erreur de connexion, reessaie.")
            term.setTextColor(colors.white)
        end
    end
end

local function computerLoginLoop()
    while true do
        if currentPlayer == nil then
            local player = authenticateKeyboard()
            currentPlayer = player
        end
        while currentPlayer ~= nil do
            sleep(0.5)
        end
    end
end

-------------------------------
-- LANCEMENT
-------------------------------

parallel.waitForAll(monitorMainLoop, computerLoginLoop)